package com.example.demo.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.example.demo.ao.BulkAo;
import com.example.demo.ao.CensusDataAo;
import com.example.demo.service.BlobService;
import com.example.demo.service.CensusDataService;
import com.example.demo.service.CensusDataSpeedService;
import com.example.demo.service.DownloadService;
//import com.example.demo.service.Impl.PoiExcelExportService;
import com.example.demo.vo.*;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/download")
public class DownloadController {


    @Autowired
    private DownloadService downloadService;

    @Autowired
    private BlobService blobService;


    @Autowired
    private CensusDataService censusDataService;


    @Autowired
    private CensusDataSpeedService censusDataSpeedService;

//    @Autowired
//    private PoiExcelExportService poiExcelExportService;


    @GetMapping("/export")
    public void exportData(HttpServletResponse response, BulkAo bulkAo) throws IOException {
//        List<DownloadVo> data = new ArrayList<>();
//        // 填充数据
//        DownloadVo downloadVo = new DownloadVo();
//        downloadVo.setName("年龄1");
//        downloadVo.setUrl("http://localhost:8080/download/download1.xlsx");
//        downloadVo.setAge(18);
//        data.add(downloadVo);


        List<BulkVo> bulkVos = downloadService.downloadInfo(bulkAo);
//        System.out.println(bulkVos);

        String fileName = "中文.xlsx";
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
//        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        EasyExcel.write(response.getOutputStream(), BulkVo.class).sheet("Sheet1").doWrite(bulkVos);
    }


    @GetMapping("/downloadUserInfo")
    public void exportUserInfo(HttpServletResponse response) throws IOException {
        List<BulkUserVo> bulkUserVos = downloadService.downloadUserInfo();
        class Export {
            public String getMgtOrgCode() {
                return mgtOrgCode;
            }

            public void setMgtOrgCode(String mgtOrgCode) {
                this.mgtOrgCode = mgtOrgCode;
            }

            public String getType() {
                return type;
            }

            public void setType(String type) {
                this.type = type;
            }

            @ExcelProperty("供电单位")
            private String mgtOrgCode;
            @ExcelProperty("类型")
            private String type;
        }
        Export export1 = new Export();
        List<Export> export = new ArrayList<>();

        for (BulkUserVo bulkUserVo : bulkUserVos) {
            export1.setMgtOrgCode(bulkUserVo.getMgtOrgCode());
            export1.setType(bulkUserVo.getType());
        }
        export.add(export1);
//        ExcelWriter writer = ExcelUtil.getWriter( + "/用户信息。xlsx");
        System.out.println(export);
        String fileName = "type.xlsx";
//        List<List<String>> head = new ArrayList<>();
//        List<String> headRow = new ArrayList<>();
//        headRow.add("用户编号");
//        headRow.add("电价码");
//        headRow.add("供电单位");
//        headRow.add("类型");
//        head.add(headRow);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        EasyExcel.write(response.getOutputStream(), Export.class).sheet("Sheet1").doWrite(export);
    }


    @GetMapping("/exportSome")
    public void exportSome(HttpServletResponse response, BulkAo bulkAo) throws IOException {
        List<BulkUserVo> bulkVos = downloadService.downloadUserInfo();
        List<ExportSomeVo> objects = new ArrayList<>();
        for (BulkUserVo bulkVo : bulkVos) {
            ExportSomeVo exportSomeVo = new ExportSomeVo();
            System.out.println(bulkVo);
            exportSomeVo.setMgtOrgCode(bulkVo.getMgtOrgCode());
            exportSomeVo.setType(bulkVo.getType());
            objects.add(exportSomeVo);
        }

        String fileName = "部分导出.xlsx";
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        EasyExcel.write(response.getOutputStream(), ExportSomeVo.class).sheet("Sheet1").doWrite(objects);
    }


    @PostMapping("upload/file")
    public String upLoadFile(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return "文件为空,请重新上传";
        }
        String fileName = file.getOriginalFilename();
        String path = "C:\\Users\\20446\\Desktop\\" + IdUtil.fastSimpleUUID() + "_" + fileName;
        try {
            FileUtil.writeBytes(file.getBytes(), path);
            return "上传成功,路劲为：" + path;
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败:" + e.getMessage();
        }
    }




    @PostMapping("/upload/excel")
    public String upLoadTxtFile(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return "文件为空,请重新上传";
        }
        try {
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            reader.addHeaderAlias("用户编号", "custNo");
            reader.addHeaderAlias("电价码", "prcCode");
            reader.addHeaderAlias("供电单位", "mgtOrgCode");
            reader.addHeaderAlias("类型", "type");
            reader.addHeaderAlias("电费年月", "qtyChargYm");
            List<BulkUserVo> tests = reader.readAll(BulkUserVo.class);
            // 调用Service层方法将数据存入数据库
            int insertedCount = downloadService.insertTests(tests);
            return "文件上传成功，共插入 " + insertedCount + "条记录";
        } catch (IOException e) {
            e.printStackTrace();
            return "文件上传失败：" + e.getMessage();
        }
    }



    @GetMapping("/dwnload/image")
    public void getImage(HttpServletResponse response) throws IOException {
        List<BlobVo> imageList = blobService.getImage();

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("图片导出_" + System.currentTimeMillis(), "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        // 使用EasyExcel导出
        EasyExcel.write(response.getOutputStream(), BlobVo.class)
                .autoCloseStream(true)
                .sheet("图片数据")
                .doWrite(imageList);
    }






    @PostMapping("/image/id")
    public List<ImageVo> getAllImage(){
        List<ImageVo> allImage = blobService.getAllImage();
        return allImage;
    }





    @GetMapping("/dwnload/image/arr")
    public void getImageArr(HttpServletResponse response) throws IOException {
        List<CensusImageVo> imageList = blobService.censusImage();

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("图片导出_" + System.currentTimeMillis(), "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        // 使用EasyExcel导出
        EasyExcel.write(response.getOutputStream(), CensusImageVo.class)
                .autoCloseStream(true)
                .sheet("图片数据")
                .doWrite(imageList);
    }





    @GetMapping("/dwnload/image/census/data")
    public void censusData(HttpServletResponse response, CensusDataAo censusDataAo) throws IOException {
        List<CensusDataVo> imageList = censusDataService.censusData(censusDataAo);

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("普查信息导出" + System.currentTimeMillis(), "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        // 创建表头样式
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 设置表头水平居中
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        // 设置表头垂直居中
        headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        // 创建内容样式
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        // 设置内容水平居中
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        // 设置内容垂直居中
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        // 创建样式策略
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
        // 使用EasyExcel导出
        EasyExcel.write(response.getOutputStream(), CensusDataVo.class)
                .registerWriteHandler(horizontalCellStyleStrategy)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) //自动列宽
                .autoCloseStream(true)
                .sheet("普查信息")
                .doWrite(imageList);
    }




    @GetMapping("/dwnload/image/census/data/speed")
    public void censusDataSpeed(HttpServletResponse response, CensusDataAo censusDataAo) throws IOException {
        List<CensusDataVo> imageList = censusDataSpeedService.censusDataSpeed(censusDataAo);

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("普查信息导出" + System.currentTimeMillis(), "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        // 创建表头样式
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 设置表头水平居中
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        // 设置表头垂直居中
        headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        // 创建内容样式
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        // 设置内容水平居中
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        // 设置内容垂直居中
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        // 创建样式策略
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
        // 使用EasyExcel导出
        EasyExcel.write(response.getOutputStream(), CensusDataVo.class)
                .registerWriteHandler(horizontalCellStyleStrategy)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) //自动列宽
                .autoCloseStream(true)
                .sheet("普查信息")
                .doWrite(imageList);
    }

}


